package com.ydlclass.serialize;

import com.ydlclass.compress.Compress;
import com.ydlclass.config.ObjectWrapper;
import com.ydlclass.serialize.impl.FstSerialize;
import com.ydlclass.serialize.impl.HessianSerialize;
import com.ydlclass.serialize.impl.JdkSerialize;
import com.ydlclass.serialize.impl.JsonSerialize;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 序列化工厂方法
 * @Author duWenJian
 * @Date 2024/2/23 14:52
 * @Version 1.0
 */
@Slf4j
public class SerializerFactory {

    public static final Map<String, ObjectWrapper<Serialize>> SERIALIZE_MAP = new ConcurrentHashMap<>(16);
    public static final Map<Byte,ObjectWrapper<Serialize>> SERIALIZE_CODE_MAP = new ConcurrentHashMap<>(16);

    static {

        ObjectWrapper<Serialize> jdk = new ObjectWrapper<>((byte) 1, "jdk", new JdkSerialize());
        ObjectWrapper<Serialize> json = new ObjectWrapper<>((byte) 2, "json", new JsonSerialize());
        ObjectWrapper<Serialize> hessian = new ObjectWrapper<>((byte) 3, "hessian", new HessianSerialize());
        ObjectWrapper<Serialize> fst = new ObjectWrapper<>((byte) 4, "fst", new FstSerialize());
        SERIALIZE_MAP.put("jdk", jdk);
        SERIALIZE_MAP.put("json", json);
        SERIALIZE_MAP.put("hessian", hessian);
        SERIALIZE_MAP.put("fst", fst);
        SERIALIZE_CODE_MAP.put((byte)1,jdk);
        SERIALIZE_CODE_MAP.put((byte)2,json);
        SERIALIZE_CODE_MAP.put((byte)3,hessian);
        SERIALIZE_CODE_MAP.put((byte)4,fst);
    }

    public static ObjectWrapper<Serialize> getSerializer(String serializeType) {
        ObjectWrapper<Serialize> wrapper = SERIALIZE_MAP.get(serializeType);
        if (wrapper == null) {
            log.debug("serializeType:{} not found,use default serializeType:{}", serializeType, "jdk");
            SERIALIZE_MAP.get("jdk");
        }

        return wrapper;
    }

    public static ObjectWrapper<Serialize> getSerializer(byte serializeCode) {
        ObjectWrapper<Serialize> wrapper = SERIALIZE_CODE_MAP.get(serializeCode);
        if (wrapper == null) {
            log.debug("serializeCode:{} not found,use default serializeCode:{}", serializeCode, 1);
            SERIALIZE_CODE_MAP.get(1);
        }
        return wrapper;
    }

    /**
     * 添加具体的序列化实现到工厂中
     * @param wrapper
     */
    public static void addSSerialize(ObjectWrapper<Serialize> wrapper){
        SERIALIZE_MAP.put(wrapper.getType(),wrapper);
        SERIALIZE_CODE_MAP.put(wrapper.getCode(), wrapper);
    }
}
